/*============================================================================*
 * FILE:                 E X A M P L E _ B M 1 . C
 *============================================================================*
 *
 * COPYRIGHT (C) 2001 - 2007 BY
 *          GE FANUC EMBEDDED SYSTEMS, INC., SANTA BARBARA, CALIFORNIA
 *          ALL RIGHTS RESERVED.
 *
 *          THIS SOFTWARE IS FURNISHED UNDER A LICENSE AND MAY BE USED AND
 *          COPIED ONLY IN ACCORDANCE WITH THE TERMS OF SUCH LICENSE AND WITH
 *          THE INCLUSION OF THE ABOVE COPYRIGHT NOTICE.  THIS SOFTWARE OR ANY
 *          OTHER COPIES THEREOF MAY NOT BE PROVIDED OR OTHERWISE MADE
 *          AVAILABLE TO ANY OTHER PERSON.  NO TITLE TO AND OWNERSHIP OF THE
 *          SOFTWARE IS HEREBY TRANSFERRED.
 *
 *          THE INFORMATION IN THIS SOFTWARE IS SUBJECT TO CHANGE WITHOUT
 *          NOTICE AND SHOULD NOT BE CONSTRUED AS A COMMITMENT BY GE FANUC
 *          EMBEDDED SYSTEMS.
 *
 *===========================================================================*
 *
 * FUNCTION:    EXAMPLE PROGRAM
 *              This is a basic example program that sets up a simple
 *				Bus Monitor.  User will be prompted for a filename (BMD
 *				file) and the the number of messages to capture, program
 *				will then capture those messages and write to the BMD file.
 *				Use BusTools/1553 (demo version or full version) to view
 *				the BMD file.
 *
 *				Since this is a monitor only example, you obviously will 
 *				need something else generating bus traffic so there will be
 *				messages to capture.
 *				
 *===========================================================================*/

/* $Revision:  X.xx Release $
   Date        Revision
  ----------   ---------------------------------------------------------------
	05/15/01	Initial version.  RSW
	05/25/01	Minor cleanup, added MY_CARD_NUM to call to BusTools_API_Close.
	03/15/02	Removed conio.h and getc calls.  RSW.
	02/17/03    Modified so that we don't use Windows-only API functions.  RSW.
    09/20/04    Added option to initialize with BusTools_API_LoadChannel.  RSW
*/
#include "mergeToVx.h"
#include "busapi.h"
#include <stdio.h>


//----------------------- Initializion Method Selection ---------------------------
// There are two methods of initializing the board:
//      1.  BusTools_API_InitExtended() - This is the "old-style" method.  It is
//          a bit more complicated but it applies to all platforms and products.
//
//      2.  BusTools_API_OpenChannel() - This is the "New, improved" method.  This
//          is less complicated (fewer parameters to get right), but does not work
//          with all possible platforms and products.  See the documentation in
//          the Software Reference Manual for this function to determine if this
//          method can be used with your platform and product.  This method is 
//          available with API version 5.10 and later.
//
// If you want to use method 1, define _USE_INIT_EXTENDED_.
// If you want to use method 2, comment out the definition for _USE_INIT_EXTENDED_.

//#define _USE_INIT_EXTENDED_


#ifdef _USE_INIT_EXTENDED_

// Constants for device information needed by BusTools_API_InitExtended.
// MODIFY THESE CONSTANTS TO MATCH YOUR CONFIGURATION, refer to documentation
// on the BusTools_API_InitExtended function for help.
#define MY_CARD_NUM		0
#define MY_BASE_ADDR	0
#define MY_IO_ADDR		0
#define MY_PLATFORM		PLATFORM_PC
#define MY_CARD_TYPE	PCCD1553
#define MY_CARRIER		NATIVE
#define MY_CHANNEL		CHANNEL_1
#define MY_MAPPING		CARRIER_MAP_DEFAULT

#else

// Constants to be used as parameters to BusTools_FindDevice and 
// BusTools_API_OpenChannel.
// MODIFY TO MATCH YOUR CONFIGURATION.
#define MY_CARD_TYPE	CPCI1553// CPCI1553// PCCD1553//
#define MY_INSTANCE     1
#define MY_CHANNEL		CHANNEL_1

#endif
//---------------------------------------------------------------------------------



// Number of BM message buffers we will use
#define NUM_BM_BUFFERS	100

// Main program
void test_bm1() {
	UINT				status, ch_id;
	BT_UINT				num_bm_buffers_actual;
	API_BM_MBUF			messages[NUM_BM_BUFFERS];
	UINT				i, num_buffers_read, num_msgs_to_capture;
	int					max_buffers_read = 0;
	int					msg_count = 0;
	FILE				*BMDfile;

	char				c;

#ifdef _USE_INIT_EXTENDED_
	unsigned int	flag = 1;	// API init flag (1=SW ints, 2=HW ints).
#else
    int dev_num, mode;
#endif
	char				filename[80]= "t1.bin";
    // Get filename, open BMD file to write
	printf("Input filename to store messages (.bmd extension): ");	
	//scanf("%s",&filename);
   
	printf("Opening BMD file %s . . . ",filename);
	if ((BMDfile = fopen(filename, "wb")) == NULL) {
		printf("ERROR OPENING FILE!\n");
	}
	else {
		printf("Success.\n\n");

//-------------------------- Initialize API and board -----------------------------
#ifdef _USE_INIT_EXTENDED_

	printf("Initializing API with BusTools_API_InitExtended . . . ");
	status = BusTools_API_InitExtended(MY_CARD_NUM, MY_BASE_ADDR, MY_IO_ADDR, &flag, 
		MY_PLATFORM, MY_CARD_TYPE, MY_CARRIER, MY_CHANNEL, MY_MAPPING);

    ch_id = MY_CARD_NUM;


#else

	printf("Initializing API with BusTools_API_OpenChannel . . . ");

    // First find the device based on type and instance.
    dev_num = BusTools_FindDevice(MY_CARD_TYPE, MY_INSTANCE);
    if (dev_num < 0) printf("ERROR IN BUSTOOLS_FINDDEVICE.\n");

    // Open the device and get the channel id.
    mode = API_B_MODE | API_SW_INTERRUPT;  // 1553B protocol, use SW interrupts.
    status = BusTools_API_OpenChannel( &ch_id, mode, dev_num, MY_CHANNEL);

#endif
//---------------------------------------------------------------------------------

		if (status == API_SUCCESS) {
			printf("Success.\n");

			// Initialize and reset memory.
			//printf("BM Init . . . ");
			//status = BusTools_BM_Init(ch_id, 1, 1);
			//if (status != API_SUCCESS) printf("ERROR = %d\n",status);

			// Select External Bus.
			printf("Bus select . . . ");
			status = BusTools_SetInternalBus(ch_id, 0);
			if (status != API_SUCCESS) printf("ERROR = %d\n",status);

			printf("BM MSG Alloc . . . ");
			status = BusTools_BM_MessageAlloc(ch_id, NUM_BM_BUFFERS, &num_bm_buffers_actual, BT1553_INT_END_OF_MESS);
			if (status != API_SUCCESS) printf("ERROR = %d\n",status);
			if (num_bm_buffers_actual != NUM_BM_BUFFERS)
				printf("ONLY %d BM BUFFERS ALLOCATED, %d REQUESTED.\n",num_bm_buffers_actual,NUM_BM_BUFFERS);

			// By default the API enables capture of messages for all RT/SA/TR/WC combinations.
			// You can set filters to limit monitored messages to specific RT/SA/TR/WC combinations
			// by using the BusTools_BM_FilterWrite function.

			// Prompt user for number of messages to capture.
			printf("\nNumber of messages to capture? ");
			//scanf("%d",&num_msgs_to_capture);

			printf("Input anything to start monitoring.\n");
			//getchar();
			//scanf("%c",&c);
			num_msgs_to_capture = 10;
			// Start monitoring.
			printf("BM Start . . . ");
			status = BusTools_BM_StartStop(ch_id, 1);
			if (status != API_SUCCESS) printf("ERROR = %d\n",status);
			else {
				printf("\n");
				while (msg_count < num_msgs_to_capture) {
					//logMsg("Message count = %d\r",msg_count,0,0,0,0,0);

					// Read a block of messages, write them to the BMDfile.
					// Note - this code just reads messages as fast as it can.  You would usually
					// put an appropriate delay here based on volume of message traffic, number
					// of message buffers used, and other tasks the computer needs to handle.
					//status = BusTools_BM_MessageReadBlock(ch_id, messages, NUM_BM_BUFFERS, 0, &num_buffers_read);
					status = BusTools_BM_ReadLastMessageBlock(ch_id, -1, -1, -1, &num_buffers_read, messages);
					if (num_buffers_read > 0) {
						// Keep track of max buffers read so we can tell if we get close to
						// overflowing our NUM_BM_BUFFERS.
						if (num_buffers_read > max_buffers_read)
							max_buffers_read = num_buffers_read;

						// Write the messages to the output file.
						for (i=0; i<num_buffers_read; i++) {
							fwrite(&messages[i], sizeof(messages[i]), 1, BMDfile);
							msg_count++;
						} // End of for (num_buffers_read)
					} // End of if (num_buffers_read > 0)
					taskDelay(0);
				} // End of while (msg_count)
				printf("Message count = %d\n",msg_count);  // display final message count.
				printf("Max buffers read = %d\n",max_buffers_read); // Show max buffers read.
			} // End of if (BM Start failed) else
		
			// We're done.  Close API and board
			printf("\nClosing API . . . ");
			status = BusTools_API_Close(ch_id);
			if (status == API_SUCCESS)
				printf("Success.\n");
			else 
				printf("FAILURE, error = %d\n", status);

			fclose(BMDfile);  // Close the output file.

		} // End of if (initialization successful)
		else printf("FAILURE, error = %d\n", status);
	} // End of if (file open failure) else
	printf("FINISHED.\n");
} // End of main
